<template>
  <div class="category-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>试题分类管理</span>
          <el-button type="primary" @click="showAddDialog">
            添加分类
          </el-button>
        </div>
      </template>

      <el-row :gutter="20">
        <!-- 分类树 -->
        <el-col :span="8">
          <el-card shadow="never">
            <template #header>
              <div class="tree-header">
                <span>分类结构</span>
                <el-button
                  type="primary"
                  link
                  @click="expandAll"
                >
                  {{ isExpandAll ? '收起' : '展开' }}全部
                </el-button>
              </div>
            </template>
            <el-tree
              ref="categoryTree"
              :data="categories"
              :props="defaultProps"
              node-key="id"
              default-expand-all
              :expand-on-click-node="false"
              @node-click="handleNodeClick"
            >
              <template #default="{ node, data }">
                <span class="custom-tree-node">
                  <span>{{ node.label }}</span>
                  <span class="node-actions">
                    <el-button
                      type="primary"
                      link
                      @click.stop="handleEdit(data)"
                    >
                      编辑
                    </el-button>
                    <el-button
                      type="danger"
                      link
                      @click.stop="handleDelete(node, data)"
                    >
                      删除
                    </el-button>
                  </span>
                </span>
              </template>
            </el-tree>
          </el-card>
        </el-col>

        <!-- 分类详情 -->
        <el-col :span="16">
          <el-card v-if="currentCategory" shadow="never">
            <template #header>
              <div class="detail-header">
                <span>{{ currentCategory.name }}</span>
                <div class="category-stats">
                  <el-tag>试题数：{{ currentCategory.questionCount }}</el-tag>
                  <el-tag type="success">已使用：{{ currentCategory.usageCount }}</el-tag>
                </div>
              </div>
            </template>

            <el-descriptions :column="2" border>
              <el-descriptions-item label="分类编码">
                {{ currentCategory.code }}
              </el-descriptions-item>
              <el-descriptions-item label="创建时间">
                {{ currentCategory.createTime }}
              </el-descriptions-item>
              <el-descriptions-item label="上级分类">
                {{ currentCategory.parentName || '无' }}
              </el-descriptions-item>
              <el-descriptions-item label="排序">
                {{ currentCategory.sort }}
              </el-descriptions-item>
              <el-descriptions-item label="描述" :span="2">
                {{ currentCategory.description }}
              </el-descriptions-item>
            </el-descriptions>

            <!-- 试题列表 -->
            <div class="question-list">
              <h3>分类下的试题</h3>
              <el-table :data="categoryQuestions" style="width: 100%">
                <el-table-column prop="title" label="题目" show-overflow-tooltip />
                <el-table-column prop="type" label="类型" width="100">
                  <template #default="scope">
                    {{ questionTypeMap[scope.row.type] }}
                  </template>
                </el-table-column>
                <el-table-column prop="difficulty" label="难度" width="100">
                  <template #default="scope">
                    {{ difficultyMap[scope.row.difficulty] }}
                  </template>
                </el-table-column>
                <el-table-column label="操作" width="100">
                  <template #default="scope">
                    <el-button
                      type="primary"
                      link
                      @click="viewQuestion(scope.row)"
                    >
                      查看
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </el-card>

    <!-- 分类编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '添加分类' : '编辑分类'"
      width="500px"
    >
      <el-form
        ref="categoryForm"
        :model="categoryForm"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="分类名称" prop="name">
          <el-input v-model="categoryForm.name" />
        </el-form-item>

        <el-form-item label="分类编码" prop="code">
          <el-input v-model="categoryForm.code" />
        </el-form-item>

        <el-form-item label="上级分类" prop="parentId">
          <el-tree-select
            v-model="categoryForm.parentId"
            :data="categories"
            :props="defaultProps"
            check-strictly
            default-expand-all
            placeholder="请选择上级分类"
          />
        </el-form-item>

        <el-form-item label="排序" prop="sort">
          <el-input-number
            v-model="categoryForm.sort"
            :min="0"
            :max="999"
          />
        </el-form-item>

        <el-form-item label="描述" prop="description">
          <el-input
            v-model="categoryForm.description"
            type="textarea"
            :rows="3"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

// 题型映射
const questionTypeMap = {
  single: '单选题',
  multiple: '多选题',
  blank: '填空题',
  programming: '编程题'
}

// 难度映射
const difficultyMap = {
  easy: '简单',
  medium: '中等',
  hard: '困难'
}

// 树形配置
const defaultProps = {
  children: 'children',
  label: 'name'
}

// 分类数据（模拟）
const categories = ref([
  {
    id: 1,
    name: 'C语言基础',
    code: 'C_BASIC',
    children: [
      {
        id: 11,
        name: '数据类型',
        code: 'C_BASIC_TYPE',
        questionCount: 15,
        usageCount: 8
      },
      {
        id: 12,
        name: '运算符',
        code: 'C_BASIC_OPERATOR',
        questionCount: 20,
        usageCount: 12
      }
    ]
  },
  {
    id: 2,
    name: '指针',
    code: 'C_POINTER',
    questionCount: 30,
    usageCount: 25
  }
])

// 当前选中的分类
const currentCategory = ref(null)

// 分类下的试题（模拟数据）
const categoryQuestions = ref([
  {
    id: 1,
    title: '以下哪个不是C语言的基本数据类型？',
    type: 'single',
    difficulty: 'easy'
  },
  {
    id: 2,
    title: '关于指针的说法，以下正确的是：',
    type: 'multiple',
    difficulty: 'medium'
  }
])

// 展开/收起控制
const isExpandAll = ref(true)
const categoryTree = ref(null)

const expandAll = () => {
  isExpandAll.value = !isExpandAll.value
  if (isExpandAll.value) {
    categoryTree.value.expandAll()
  } else {
    categoryTree.value.collapseAll()
  }
}

// 对话框相关
const dialogVisible = ref(false)
const dialogType = ref('add')
const categoryForm = reactive({
  name: '',
  code: '',
  parentId: null,
  sort: 0,
  description: ''
})

const rules = {
  name: [
    { required: true, message: '请输入分类名称', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入分类编码', trigger: 'blur' },
    { pattern: /^[A-Z_]+$/, message: '编码只能包含大写字母和下划线', trigger: 'blur' }
  ]
}

const handleNodeClick = (data) => {
  currentCategory.value = data
}

const showAddDialog = () => {
  dialogType.value = 'add'
  Object.assign(categoryForm, {
    name: '',
    code: '',
    parentId: null,
    sort: 0,
    description: ''
  })
  dialogVisible.value = true
}

const handleEdit = (data) => {
  dialogType.value = 'edit'
  Object.assign(categoryForm, {
    name: data.name,
    code: data.code,
    parentId: data.parentId,
    sort: data.sort,
    description: data.description
  })
  dialogVisible.value = true
}

const handleDelete = (node, data) => {
  ElMessageBox.confirm(
    '确定要删除该分类吗？如果存在子分类，将一并删除。',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    // 实现删除逻辑
    ElMessage.success('删除成功')
  }).catch(() => {})
}

const handleSubmit = () => {
  // 实现提交逻辑
  dialogVisible.value = false
  ElMessage.success(dialogType.value === 'add' ? '添加成功' : '修改成功')
}

const viewQuestion = (question) => {
  // 实现查看试题逻辑
}
</script>

<style scoped>
.category-container {
  padding: 20px;
}

.tree-header,
.detail-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}

.node-actions {
  opacity: 0;
  transition: opacity 0.2s;
}

.custom-tree-node:hover .node-actions {
  opacity: 1;
}

.category-stats {
  display: flex;
  gap: 10px;
}

.question-list {
  margin-top: 20px;
}

.question-list h3 {
  margin-bottom: 15px;
}
</style> 